<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use fast\Random;
use tests\thinkphp\library\think\sessionTest;
use think\Db;

use app\common\library\User as UserService;

class Expert extends Frontend
{
    protected $noNeedLogin = ["test"];
    protected $noNeedRight = '*';
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();

        $user = $this->auth->getUser();
        if(!$user){
            $this->redirect(url("/index/user/login"));
        }
    }
    public function test() {
        $pid = $this->request->param('pid',0);
        $user_array =[];
        $parentRelations = UserService::getParentRelations($pid,$pid, 1, 10, $user_array);
        echo '<pre>';
        $parentRelations = empty($parentRelations)?[]:$parentRelations;
        foreach ($parentRelations as $key => $value) {
            echo "代数{$key}=".$value['mobile'].PHP_EOL; 
        }
//        var_dump($parentRelations);
    }
    
    //达人升级-开始页
    public function index()
    {
        if(session("is_first_login")){
            // 跳转到首页
            $this->redirect("/index/index/index");
        }else{
            // 首次登录
            session("is_first_login", 1);

            $this->assign("title", "达人升级");
            $this->assign("foot_nav_index", "4");

            $upgrade_type ='0';
            $taskTotals = Db::name("expert_upgrade_order")->where(["user_id"=> $this->auth->id,"status"=>['in',[0,1]]])->order("id DESC")->find();
            if(!empty($taskTotals)){
                $upgrade_type =$taskTotals['upgrade_type'];
            }
            $this->assign("upgrade_type", $upgrade_type);
            return $this->view->fetch();
        }
    }

    //达人升级-选择产品
    public function choose()
    {
        $this->assign("title", "选择产品-达人升级");
        $this->assign("foot_nav_index", "4");

        //升级配置
        $level = $this->request->param("level");
        $taskTotals = Db::name("expert_upgrade_order")->where(["user_id"=>$this->auth->id,"status"=>['in',[0,1]]])->count();
        if($taskTotals){
//            $this->success("存在未完成任务",'',["level" => $level]);
            
            //没有选择商品
            $goods = db("expert_upgrade_goods")->where("upgrade_type", $level)->where("user_id", $this->auth->id)->count();
            if(empty($goods)){
                 $this->redirect("/index/task/upgrade", ["level" => $level]);
            }
            
            $this->redirect("index/expert/orderShow", ["level" => $level]);
        }
        
        $expert_upgrade_config = db("expert_upgrade_config")->where("level", $level)->find();
        // exit(print_r($expert_upgrade_config));
        $this->assign("expert_upgrade_config", $expert_upgrade_config);
        $this->assign("level", $level);

        //当前配置的商品
        $goods_list = db("goods")->where("expert_level", $level)->orderRaw("expert_level asc ,weigh asc")->select();
        // exit(print_r($goods_list));
        // $this->assign("goods_list", $goods_list);

        //推荐人的商品列表
        $p1_goods_list = [];
        //店铺的商品列表
        $p2_goods_list = [];
        //级别的商品列表
        $p3_goods_list = [];
        if ($goods_list) {
            foreach ($goods_list as $goods) {
                if ($goods["position"] == "1") {
                    $p1_goods_list[] = $goods;
                }
                if ($goods["position"] == "2") {
                    $p2_goods_list[] = $goods;
                }
                if ($goods["position"] == "3") {
                    $p3_goods_list[] = $goods;
                }
            }
        }
        $this->assign("p1_goods_list", $p1_goods_list);
        $this->assign("p2_goods_list", $p2_goods_list);
        $this->assign("p3_goods_list", $p3_goods_list);

        //当前用户
        $user = $this->auth->getUser();
        if (!$user["avatar"]) {
            $user["avatar"] = letter_avatar($user["nickname"]);
        }
        $this->assign("user", $user);

        return $this->view->fetch();
    }

    //达人升级-订单生成
    public function orderAdd()
    {
        $unique_id = Random::alnum(10);
        $user = $this->auth->getUserinfo();
//         exit(print_r($user));
        $level = $this->request->post("level");
        //已经创建任务，不能在创建
       $taskTotals = Db::name("expert_upgrade_order")->where(["user_id"=>$user["id"],"status"=>['in',[0,1,-2]]])->count();
        if($taskTotals>0){
           $goods = db("expert_upgrade_goods")->where("upgrade_type", $user['upgradeing_expert_level'])->where("user_id", $user["id"])->count();
            if(empty($goods)){
                 $this->error('', url('index/Task/upgrade'));
            }else{
                $this->error('', url('index/expert/orderShow',["level" => $user['upgradeing_expert_level']]));
            }
        }
        if($user['upgradeing_expert_level']>0){
            //正在升级中，则跳转到该等级任务列表
            $this->error('', 'index/Task/upgrade');
        }
        // exit($level."");
        if($user['expert_level']>$level){ //完成的就不能给用户再创建
           $this->error('','index/Task/upgrade');
        }
        
        // exit($level."");
        $parent_user_params = $this->request->post("parent_user/a", [], 'strip_tags');
        $company_store_params = $this->request->post("company_store/a", [], 'strip_tags');
        $relation_line_params = $this->request->post("relation_line/a", [], 'strip_tags');

        //公司帐号：
        $company_account = db("user")->where("is_company_account", 1)->find();

        $order_goods_datas = [];
        $orders = [];

        if ($parent_user_params) {
            foreach ($parent_user_params as $param) {
                $array = json_decode($param, true);
                // exit(print_r($array));
                $goodsid = $array["goodsid"];
                $number = $array["number"];
                $goodstype = $array["goodstype"];
                $price = $array["price"];
                $order_goods_datas[] = [
                    "upgrade_type" => $level,
                    "goods_type" => $goodstype,
                    "goods_id" => $goodsid,
                    "price" => $price,
                    "buy_num" => $number,
                    "user_id" => $user["id"],
                    "addtime" => time(),
                    "unique_id" => $unique_id,
                ];
            }

            // 订单类型：1推荐人，2店铺，3级别订单
            $parent_user = UserService::getParent($user["parent_user_id"]);
            if(empty($parent_user)){
                $this->error("不存在的上级用户,不能下单");
            }
            // exit(print_r($parent_user));
            $orders[] = [
                "upgrade_type" => $level,
                "order_type" => 1,
                "user_id" => $user["id"],
                "up_user_id" => $parent_user["id"],
                "order_sn" => "",
                "order_amount" => 0,
                "status" => 0,
                "addtime" => time(),
                "unique_id" => $unique_id,
                "gen_level" => 1,
                "expiretime" => time() + 3600,
            ];
        }


        if ($company_store_params) {

            foreach ($company_store_params as $param) {
                $array = json_decode($param, true);
                // exit(print_r($array));
                $goodsid = $array["goodsid"];
                $number = $array["number"];
                $goodstype = $array["goodstype"];
                $price = $array["price"];
                $order_goods_datas[] = [
                    "upgrade_type" => $level,
                    "goods_type" => $goodstype,
                    "goods_id" => $goodsid,
                    "price" => $price,
                    "buy_num" => $number,
                    "user_id" => $user["id"],
                    "addtime" => time(),
                    "unique_id" => $unique_id,
                ];
            }

            // 订单类型：1推荐人，2店铺，3级别订单
            $orders[] = [
                "upgrade_type" => $level,
                "order_type" => 2,
                "user_id" => $user["id"],
                "up_user_id" => $company_account ? $company_account["id"] : 0,
                "order_sn" => "",
                "order_amount" => 0,
                "status" => 0,
                "addtime" => time(),
                "unique_id" => $unique_id,
                "gen_level" => 1,
                "expiretime" => time() + 3600,
            ];
        }

        if ($relation_line_params) {

            foreach ($relation_line_params as $key => $param) {
                $array = json_decode($param, true);
                // exit(print_r($array));
                $goodsid = $array["goodsid"];
                $number = $array["number"];
                $goodstype = $array["goodstype"];
                $price = $array["price"];
                $order_goods_datas[] = [
                    "upgrade_type" => $level,
                    "goods_type" => $goodstype,
                    "goods_id" => $goodsid,
                    "price" => $price,
                    "buy_num" => $number,
                    "user_id" => $user["id"],
                    "addtime" => time(),
                    "unique_id" => $unique_id,
                ];

                // 订单类型：1推荐人，2店铺，3级别订单
                // $orders[] = [
                //     "upgrade_type" => $level,
                //     "order_type" => 3,
                //     "user_id" => $user["id"],
                //     "up_user_id" => isset($parentRelations[$key]) ? $parentRelations[$key]["id"] : 0,
                //     "order_sn" => "",
                //     "order_amount" => $order_amount,
                //     "status" => 0,
                //     "addtime" => time(),
                //     "unique_id" => $unique_id,
                // ];
            }

//            echo "当前用户ID". $this->auth->id.PHP_EOL;
            
//            echo "父级user_id=". $parent_user["id"]."上一代 up_user_id". $parent_user["parent_user_id"].' mobile = '.$parent_user["mobile"].PHP_EOL;
            //查找这个用户9代单传上级
            $user_array = [];
//            $parentRelations = UserService::getParentRelations($parent_user["parent_user_id"], 2, 10, $user_array);
            $parentRelations = UserService::getParentRelations($user["parent_user_id"],$user["parent_user_id"], 1, 10, $user_array);

            foreach ($parentRelations as $key => $relation) {
                // exit(print_r($relation));
                // 订单类型：1推荐人，2店铺，3级别订单
                $orders[] = [
                    "upgrade_type" => $level,
                    "order_type" => 3,
                    "user_id" => $user["id"],
                    "up_user_id" => $relation["id"],
                    "order_sn" => "",
                    "order_amount" => 0,
                    "status" => 0,
                    "addtime" => time(),
                    "unique_id" => $unique_id,
                    "gen_level" => $key + 1,
                    "expiretime" => time() + 3600,
                ];
            }
        }

        // exit(print_r($order_goods_datas));
        // exit(print_r($orders));

        //删除原来这个级别的升级订单
        db("expert_upgrade_order")->where("upgrade_type", $level)->where("user_id", $user["id"])->delete();
        db("expert_upgrade_goods")->where("upgrade_type", $level)->where("user_id", $user["id"])->delete();

        //插入订单商品和订单
        db("expert_upgrade_goods")->insertAll($order_goods_datas);
        db("expert_upgrade_order")->insertAll($orders);

        //更新用户正在进行升级的级别
        db("user")->where("id", $user["id"])->update(["upgradeing_expert_level" => $level]);

        $this->success("添加成功", "", ["level" => $level]);
    }

    //达人升级-订单生成-跳过
    public function orderSkip()
    {
        $unique_id = Random::alnum(10);
        $user = $this->auth->getUserinfo();
//         exit(print_r($user));
        //已经创建任务，不能在创建
        $taskTotals = Db::name("expert_upgrade_order")->where(["user_id"=>$user["id"],"status"=>['in',[0,1,-2]]])->count();
        if($taskTotals>0){
           $goods = db("expert_upgrade_goods")->where("upgrade_type", $user['upgradeing_expert_level'])->where("user_id", $user["id"])->count();
            if(empty($goods)){
                 $this->error('', 'index/Task/upgrade');
            }else{
                $this->error('', url('index/expert/orderShow',["level" => $user['upgradeing_expert_level']]));
            }
        }
        if($user['upgradeing_expert_level']>0){
            //正在升级中，则跳转到该等级任务列表
            $this->error('', 'index/Task/upgrade');
        }
        
        $level = $this->request->get("level");
        // exit($level."");
        if($user['expert_level']>$level){ //完成的就不能给用户再创建
           $this->error('','index/Task/upgrade');
        }
        
        
        
        //公司帐号：
        $company_account = db("user")->where("is_company_account", 1)->find();

        $order_goods_datas = [];
        $orders = [];

            // 订单类型：1推荐人，2店铺，3级别订单
            $parent_user = UserService::getParent($user["parent_user_id"]);
            if(empty($parent_user)){
                $this->error("不存在的上级用户,不能下单");
            }
            // exit(print_r($parent_user));
            $orders[] = [
                "upgrade_type" => $level,
                "order_type" => 1,
                "user_id" => $user["id"],
                "up_user_id" => $parent_user["id"],
                "order_sn" => "",
                "order_amount" => 0,
                "status" => 0,
                "addtime" => time(),
                "unique_id" => $unique_id,
                "gen_level" => 1,
                "expiretime" => time() + 3600,
            ];


            // 订单类型：1推荐人，2店铺，3级别订单
            $orders[] = [
                "upgrade_type" => $level,
                "order_type" => 2,
                "user_id" => $user["id"],
                "up_user_id" => $company_account ? $company_account["id"] : 0,
                "order_sn" => "",
                "order_amount" => 0,
                "status" => 0,
                "addtime" => time(),
                "unique_id" => $unique_id,
                "gen_level" => 1,
                "expiretime" => time() + 3600,
            ];

//            echo "当前用户ID". $this->auth->id.PHP_EOL;
            
//            echo "父级user_id=". $parent_user["id"]."上一代 up_user_id". $parent_user["parent_user_id"].' mobile = '.$parent_user["mobile"].PHP_EOL;
            //查找这个用户9代单传上级
            $user_array = [];
//            $parentRelations = UserService::getParentRelations($parent_user["parent_user_id"], 2, 10, $user_array);
            $parentRelations = UserService::getParentRelations($user["parent_user_id"],$user["parent_user_id"], 1, 10, $user_array);
//            var_dump($parentRelations);die;
            foreach ($parentRelations as $key => $relation) {
                // exit(print_r($relation));
                // 订单类型：1推荐人，2店铺，3级别订单
                $orders[] = [
                    "upgrade_type" => $level,
                    "order_type" => 3,
                    "user_id" => $user["id"],
                    "up_user_id" => $relation["id"],
                    "order_sn" => "",
                    "order_amount" => 0,
                    "status" => 0,
                    "addtime" => time(),
                    "unique_id" => $unique_id,
                    "gen_level" => $key + 1,
                    "expiretime" => time() + 3600,
                ];
            }

        // exit(print_r($order_goods_datas));
        // exit(print_r($orders));

        //删除原来这个级别的升级订单
//        db("expert_upgrade_order")->where("upgrade_type", $level)->where("user_id", $user["id"])->delete();

        //插入订单商品和订单
        db("expert_upgrade_order")->insertAll($orders);

        //更新用户正在进行升级的级别
        db("user")->where("id", $user["id"])->update(["upgradeing_expert_level" => $level]);

        $this->success("添加成功", "", ["level" => $level]);
    }
    
    
    //达人升级-订单显示
    public function orderShow()
    {
        $this->assign("title", "订单显示-达人升级");
        $this->assign("foot_nav_index", "4");

        //当前用户
        $user = $this->auth->getUser();
        if (!$user["avatar"]) {
            $user["avatar"] = letter_avatar($user["nickname"]);
        }
        $this->assign("user", $user);

        //升级配置
        $level = $this->request->param("level");
        $expert_upgrade_config = db("expert_upgrade_config")->where("level", $level)->find();
        // exit(print_r($upgrade_config));
        $this->assign("expert_upgrade_config", $expert_upgrade_config);
        $this->assign("level", $level);

        $goods_list = db("expert_upgrade_goods")->alias('eug')->join("goods g", "g.id=eug.goods_id", "LEFT")->where("user_id", $user["id"])->where("upgrade_type", $level)->field("g.*,eug.upgrade_type,eug.goods_type,eug.price,eug.buy_num")->select();
        // exit(print_r($goods_list));

        $total_order_amount = 0;

        //推荐人的商品列表
        $p1_goods_list = [];
        $p1_order_amount = 0;

        //店铺的商品列表
        $p2_goods_list = [];
        $p2_order_amount = 0;

        //级别的商品列表
        $p3_goods_list = [];
        $p3_order_amount = 0;
        if ($goods_list) {
            foreach ($goods_list as $goods) {
                if ($goods["goods_type"] == "1") {
                    $p1_goods_list[] = $goods;
                    $p1_order_amount += floatval($goods["price"]) * intval($goods["buy_num"]);
                }
                if ($goods["goods_type"] == "2") {
                    $p2_goods_list[] = $goods;
                    $p2_order_amount += floatval($goods["price"]) * intval($goods["buy_num"]);
                }
                if ($goods["goods_type"] == "3") {
                    $p3_goods_list[] = $goods;
                    $p3_order_amount += floatval($goods["price"]) * intval($goods["buy_num"]);
                }
            }

            $total_order_amount = $p1_order_amount + $p2_order_amount + $p3_order_amount;
        }

        $this->assign("p1_goods_list", $p1_goods_list);
        $this->assign("p1_order_amount", $p1_order_amount);

        $this->assign("p2_goods_list", $p2_goods_list);
        $this->assign("p2_order_amount", $p2_order_amount);

        $this->assign("p3_goods_list", $p3_goods_list);
        $this->assign("p3_order_amount", $p3_order_amount);

        $this->assign("total_order_amount", $total_order_amount);

        return $this->view->fetch();
    }

}
